import { applyMiddleware, combineReducers, createStore } from 'redux';
import thunk from 'redux-thunk';

let contexts;
const store = createStore(getReducers(), applyMiddleware(thunk)); // 创建store
if (module.hot) {
  // HMR支持
  module.hot.accept(contexts.id, function () {
    store.replaceReducer(getReducers());
  });
}

/**
 * 初始化reducer
 * 自动查询引入`reducers`目录下的所有文件
 * export default 作为reducer
 */
function getReducers() {
  contexts = require.context('./reducers/', true, /\.js$/i);
  const getReducerName = (contextKey) => {
    return contextKey
      .split(/\.?\//g) // 切分路径名
      .filter(Boolean) // 过滤空字符串
      .join('.') // 小数点连接
      .replace(/(\.index)?\.js$/i, '') // 去掉后缀名
      .replace(/[-_]+./g, (str) => str.substr(-1).toUpperCase());
  };

  // 如果需要引入其他reducer, 合并到这个对象中
  let reducers = contexts.keys().reduce((ret, key) => ({ ...ret, [getReducerName(key)]: contexts(key).default }), {});

  return combineReducers(reducers);
}

export default store;
